package com.wzh.springsecurity.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     *授权
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所以人可以访问，功能页只有对应有权限的人才可以访问
        //请求授权的规则
        http.authorizeRequests().antMatchers("/").permitAll()
                                .antMatchers("/level1/**").hasRole("vip1")
                                .antMatchers("/level2/**").hasRole("vip2")
                                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限默认会到登录页面
        http.formLogin().loginPage("/toLogin");

        //开启注销
        //防止网站攻击：get，post
        http.csrf().disable();//关闭csrf功能，登录失败存在的问题
        http.logout().logoutSuccessUrl("/");//跳转到首页


        //开启记住我功能  cookie,默认保存两周，自定义接受前端传来的参数
        http.rememberMe().rememberMeParameter("remember");

    }

    /**
     *认证
     * 密码加密：PasswordEncoder
     * 在security5.0+中新加了很多的加密方式
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这些数据正常应该从数据库里读
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("wzh").password(new BCryptPasswordEncoder().encode("111111")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("111111")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("111111")).roles("vip1");
    }
}
